package com.djq.hhc.redis;

import cn.hutool.core.date.DateTime;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: dadd7
 * @Date: 2023/03/09/下午 4:13
 * @Description:
 */
@Component
public class RedisIdWorker {

    /**
     * 开始时间戳2023.03.10
     */
    private static final long BEGIN_TIMESTAMP = 1678484550L;

    /**
     * 序列号的位数
     */
    private static final long COUNT_BITS = 32;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long nextId(String keyPrefix) {
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIMESTAMP;
        //生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        //拼接并返回(<<位移，|或运算填充（因为前面移动后末尾都是0，或是谁是真为谁）)
        return timeStamp << COUNT_BITS | count;
    }
}
